﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using System.Windows.Media.Imaging;
using System.Drawing.Imaging;

namespace eKanbanWPF.View
{
    public static class BitmapConversion
    {

        public static Image ToWinFormsBitmap(BitmapSource bitmapsource)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BitmapEncoder enc = new PngBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(bitmapsource));
                enc.Save(stream);
                //FileStream fstream = new FileStream("b.bmp", FileMode.Create);
                //stream.WriteTo(fstream);
                //fstream.Close();

                var res =  Image.FromStream(stream);
                //res.Save("c.bmp");
                return res;
                //using (var tempBitmap = new Bitmap(stream))
                //{
                //    // According to MSDN, one "must keep the stream open for the lifetime of the Bitmap."
                //    // So we return a copy of the new bitmap, allowing us to dispose both the bitmap and the stream.
                //    var b = new Bitmap(tempBitmap);
                //    b.MakeTransparent(Color.Transparent);
                //    return b;
                //}
            }
        }

        public static BitmapSource ToWpfBitmap(Image bitmap)
        {
            //bitmap.Save("d.bmp");
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Png);

                stream.Position = 0;
                BitmapImage result = new BitmapImage();
                result.BeginInit();
                // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
                // Force the bitmap to load right now so we can dispose the stream.
                result.CacheOption = BitmapCacheOption.OnLoad;
                result.StreamSource = stream;
                result.EndInit();
                result.Freeze();
                return result;
            }
        }
    }

}
